package com.smart.common.scheduler.service;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.smart.common.enums.ConstructionStatusEnum;
import com.smart.common.enums.ReportTypeEnum;
import com.smart.common.utils.AssertUtil;
import com.smart.mapper.ProjectWeeklyItemMapper;
import com.smart.mapper.ProjectWeeklyTaskMapper;
import com.smart.model.domain.ProjectReportDO;
import com.smart.model.domain.ProjectWeeklyItemDO;
import com.smart.model.domain.ProjectWeeklyTaskDO;
import com.smart.model.domain.ProjectWeeklyTaskItemDO;
import com.smart.model.vo.ProjectVO;
import com.smart.service.ProjectReportService;
import com.smart.service.ProjectService;
import com.smart.service.ProjectWeeklyTaskItemService;
import com.smart.service.ProjectWeeklyTaskService;
import com.smart.utils.WeekUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author macbook
 */
@Slf4j
@Component
public class WeeklyTaskScheduleService {

    @Autowired
    private ProjectWeeklyTaskService projectWeeklyTaskService;
    @Autowired
    private ProjectWeeklyTaskMapper projectWeeklyTaskMapper;
    @Autowired
    private ProjectService projectService;
    @Autowired
    private ProjectReportService projectReportService;
    @Autowired
    private ProjectWeeklyItemMapper projectWeeklyItemMapper;
    @Autowired
    private ProjectWeeklyTaskItemService projectWeeklyTaskItemService;

    /**
     * 生成周报任务
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean createWeeklyTask() {
        Date date = new Date();
        //扫描所有"在施"或者"完工待验"的项目
        List<ProjectVO> projects = projectService.listProjectByStatus(Lists.newArrayList(ConstructionStatusEnum.RUNNING.getCode(), ConstructionStatusEnum.WAIT_ACCEPT.getCode()));
        if (CollectionUtils.isEmpty(projects)) {
            log.warn("不存在-在施/完工待验的项目...");
            return true;
        }

        //查询当周是否有填报项（有则生成周报任务并下发给项目）
        Date beginOfWeek = DateUtil.beginOfWeek(date).toJdkDate();
        Date endOfWeek = DateUtil.endOfWeek(date).toJdkDate();
        List<ProjectWeeklyItemDO> weekItems = projectWeeklyItemMapper.listByRangeWeek(beginOfWeek, endOfWeek);
        if (CollectionUtils.isEmpty(weekItems)) {
            log.warn("当周不存在填报项...");
            return true;
        }

        int weekNum = WeekUtil.getWeekNum();
        int yearNum = DateUtil.year(date);
        ProjectWeeklyTaskDO weeklyTaskDO = projectWeeklyTaskMapper.queryByYearAndWeek(yearNum, weekNum);
        if (weeklyTaskDO != null) {
            log.warn("当周任务已存在...");
            return true;
        }

        //生成周报任务
        ProjectWeeklyTaskDO weeklyTask = new ProjectWeeklyTaskDO();
        weeklyTask.setWeekNum(weekNum);
        weeklyTask.setYear(yearNum);
        weeklyTask.setStartTime(beginOfWeek);
        endOfWeek = DateUtil.offsetSecond(endOfWeek, -1);
        weeklyTask.setEndTime(endOfWeek);
        projectWeeklyTaskService.save(weeklyTask);

        // 将周报项和周报进行绑定
        List<ProjectWeeklyTaskItemDO> itemList = buildListDO(weeklyTask, weekItems);
        if (CollectionUtils.isEmpty(itemList)) {
            log.warn("当周不存在填报项......");
            return true;
        }
        projectWeeklyTaskItemService.saveBatch(itemList);

        //为项目生成周报任务
        List<ProjectReportDO> entityList = buildDOList(weeklyTask, projects);
        for (ProjectReportDO reportDO : entityList) {
            boolean exists = projectReportService.lambdaQuery().eq(ProjectReportDO::getTaskId, reportDO.getTaskId()).eq(ProjectReportDO::getProjectId, reportDO.getProjectId()).exists();
            if (!exists) {
                projectReportService.save(reportDO);
            }
        }
        return true;
    }

    private List<ProjectWeeklyTaskItemDO> buildListDO(ProjectWeeklyTaskDO weeklyTask, List<ProjectWeeklyItemDO> weekItems) {
        List<ProjectWeeklyTaskItemDO> list = Lists.newArrayList();
        for (ProjectWeeklyItemDO weekItem : weekItems) {
            ProjectWeeklyTaskItemDO itemDO = new ProjectWeeklyTaskItemDO();
            itemDO.setWeeklyTaskId(weeklyTask.getId());
            itemDO.setWeeklyItemId(weekItem.getId());
            list.add(itemDO);
        }
        return list;
    }

    /**
     * 构造周报任务消息
     * @param weeklyTaskDO
     * @param projects
     * @return
     */
    private List<ProjectReportDO> buildDOList(ProjectWeeklyTaskDO weeklyTaskDO, List<ProjectVO> projects) {
        List<ProjectReportDO> list = Lists.newArrayList();
        for (ProjectVO project : projects) {
            ProjectReportDO reportDO = new ProjectReportDO();
            reportDO.setProjectId(project.getId());
            reportDO.setTaskId(weeklyTaskDO.getId());
            reportDO.setItemType(ReportTypeEnum.WEEKLY.name());
            list.add(reportDO);
        }
        return list;
    }

    /**
     * 重新将所有任务下发一次，如果已经存在的任务则不在下发
     */
    public boolean resendWeeklyTask() {
        Date date = new Date();
        //扫描所有"在施"或者"完工待验"的项目
        List<ProjectVO> projects = projectService.listProjectByStatus(Lists.newArrayList(ConstructionStatusEnum.RUNNING.getCode(), ConstructionStatusEnum.WAIT_ACCEPT.getCode()));
        if (CollectionUtils.isEmpty(projects)) {
            log.info("不存在-在施/完工待验的项目...");
            return true;
        }

        List<ProjectReportDO> data = Lists.newArrayList();

        //查询所有的周报任务
        List<ProjectWeeklyTaskDO> list = projectWeeklyTaskService.list();
        for (ProjectWeeklyTaskDO weeklyTask : list) {
            //为项目生成周报任务
            List<ProjectReportDO> entityList = buildDOList(weeklyTask, projects);
            for (ProjectReportDO reportDO : entityList) {
                boolean exists = projectReportService.lambdaQuery().eq(ProjectReportDO::getTaskId, reportDO.getTaskId()).eq(ProjectReportDO::getProjectId, reportDO.getProjectId()).exists();
                if (!exists) {
                    data.add(reportDO);
                }
            }
        }

        if (CollectionUtils.isNotEmpty(data)) {
            log.info("重新发送周报任务条数 {}", data.size());
            Map<Long, List<ProjectReportDO>> collect = data.stream().collect(Collectors.groupingBy(ProjectReportDO::getProjectId));
            log.info("重新发送周报任务项目 {}", JSON.toJSONString(collect));
            projectReportService.saveOrUpdateBatch(data);
        }
        return true;
    }
}
